import React,{useState,useRef, useEffect} from 'react'
import { View,Image,Text } from '@tarojs/components'
import Taro,{ useDidShow, useReachBottom } from '@tarojs/taro'
import { StatusAction } from './status/index';
import Tabs from './tabs';

import './index.less'

const tabsList = [
  {
    label: '全部',
    value: 0,
  },
  {
    label: '待付款',
    value: 1,
  },
  {
    label: '待收货',
    value: 2,
  },
  {
    label: '待使用',
    value: 3,
  },
  {
    label: '待评价',
    value: 4,
  },
  {
    label: '退款/售后',
    value: 5,
  },
];
export default function OrderList() {
  const [params, setparams] = useState({
    page:1,
    pageSize:10,
    total:0
  })
  const [moreStatus, setmoreStatus] = useState('more')
  const [orderList, setorderList] = useState([])
  const [curTab, setCurTab] = useState(null);
  const [isOpened, setIsOpened] = useState(false);
  const opOrderId = useRef();
  const orderPage = useRef(null);
  const flags = useRef({ isLoading: false, finished: false });

  useEffect(()=>{
    setCurTab(0)
  },[])
  useEffect(()=>{
    _initData({page:1,curTab})
  },[curTab])
  const handleTabChanged = (index) => {
    setCurTab(index)
  };
  useReachBottom(()=>{
    if(params.total == params.pageSize){
      _initData({page:params.page+1},data=>{
        let arr = [...orderList]
        arr.push(...data)
        setorderList(arr)
        setmoreStatus("no-more")
      })
    }else{
      setmoreStatus("no-more")
    }
  })

  function handleToDetail(e){   ///  点击详情
    let url = ''
    if(e.orderSource == 1){
      url = `/orderSubPack/orderDetail/index?orderId=${e.orderId}`;
    }
    if(e.orderSource == 2){
      if(Taro.$channel?.includes('cinema')){
        url = `/mineSubPack/order-detail/index?id=${e.orderId}`
      }
      if(Taro.$channel?.includes('movie')){
        url = `/orderSubPack/cinemaDetail/index?orderId=${e.orderId}`;  /// 玩票详情
      }
    }
    if(e.orderSource == 3){
      url = `/orderSubPack/movieDetail/index?orderId=${e.orderId}`;
    }
    if(e.orderSource == 4){
      url = `/orderSubPack/goodsDetail/index?orderId=${e.orderId}`;
    }
    if(e.orderSource == 6){
      url = `/orderSubPack/powerDetail/index?orderId=${e.orderId}`;
    }
    if(e.orderSource == 11){
      url = `/mineSubPack/food-detail/index?id=${e.orderId}`
    }
    if(e.orderSource == 5 || e.orderSource == 9 || e.orderSource == 8){
      url = `/orderSubPack/card-detail/index?orderId=${e.orderId}&type=${e.orderSource}`;
    }
    if(e.isOpenOrder){
      url = `/orderSubPack/activityDetail/index?orderId=${e.orderId}`;
    }
    Taro.navigateTo({
      url
    })
  }
  
  ////     network
  const _initData = async(e,func)=>{
    setmoreStatus('loading')
    const data = {
      page:params.page,
      pageSize:params.pageSize,
      status:curTab,
      orderSource:Taro.getCurrentInstance().router?.params?.status || '',
      ...e
    }
    if(data.status>0 || data.status === 0){
      Taro.showLoading({
        title:'加载中...'
      })
      const res = await Taro.$post('/order/users/orders',data,1)
      if(res.code === '1'){
        setmoreStatus('more')
        setparams({...data,total:res.content.length})
        if(func){
          func(res.content)
          return;
        }
        setorderList(res.content)
      }
    }
  }

  return (
    <View className="order-list">
      <Tabs tabsList={tabsList} getCurrentTab={handleTabChanged} curTab={curTab} />
      {!orderList.length?
      <View className="var-empty">
        <Image src={require('@/static/empty.png')} mode="widthFix" style="width: 50vw;"></Image>
      </View>:null}
      {orderList.map(order=>{
        return <View className="list-item normal" key={order.orderId}>
          <View className="item-header">
            {order.sellerUserAvatar?<Image className="image" src={order.sellerUserAvatar} />:null}
            <View style={{display:'flex',alignItems:'center',fontWeight:600}}>{order.sellerUserName || ''} <Text style={{color:'#000',fontSize:12}} className='at-icon at-icon-chevron-right'></Text></View>
            <Text style={{color:order.statusColor}} className='span'>{order.statusDesc}</Text>
          </View>
          {order.orderSource == 1 || (order.orderSource == 11 && order.orderItemInfos.length == 1)?<>
          {order.orderItemInfos?.map(res=>(
            <View className="item-main shops-goods" onClick={() => handleToDetail(order)}>
              <Image className="main-img" mode="aspectFill" src={res.mainImageUrl} />
              <View className="main-info">
                <View className="omit-2 h2">{res.title}</View>
                <View className='p'>{res.generalSizeText}</View>
              </View>
              <View className="main-price">
                <View className="price-p"><Text style={{fontSize:'10px'}}>￥</Text> {res.price}</View>
                共 {res.quantity} 件
              </View>
            </View>
          ))}</>:null}
          {order.orderSource == 5 || order.orderSource == 9 || order.orderSource == 8?<>
          {order.orderItemInfos?.map(res=>(
            <View className="item-main shops-goods" onClick={() => handleToDetail(order)}>
              <Image className="main-img" mode="aspectFill" src={res.mainImageUrl} />
              <View className="main-info">
                <View className="omit-2 h2">{res.title}</View>
                {order.orderSource == 8?<View className='p'>{res.generalSizeText}</View>:null}
              </View>
              <View className="main-price">
                <View className="price-p"><Text style={{fontSize:'10px'}}>￥</Text> {res.price}</View>
              </View>
            </View>
          ))}</>:null}
          {order.orderSource == 2 || order.orderSource == 3?<>
          {order.orderItemInfos?.map(res=>(
          <View className="item-main movie-goods" onClick={() => handleToDetail(order)}>
            <Image className="main-img" src={res.mainImageUrl} />
            <View className="main-info">
              {order.orderSource == 2?<>
                <View className="omit-2 h2">{res.movieName + ' '+ res.quantity}张</View>
                <View className='p'>{res.timeFormat}</View>
                <View className='p'>{res.hallName + ' ' +res.seatNames}</View>
              </>:<>
                <View className="omit-2 h2">{res.scheduleTitle}</View>
                <View className='p'>{res.timeFormat}</View>
                <View className='p'>{res.locationName}</View>
              </>}
            </View>
          </View>
          ))}</>:null}
          {order.orderSource == 4 || (order.orderSource == 11 && order.orderItemInfos.length>1)?
          <View className="item-main foods-goods" onClick={() => handleToDetail(order)}>
            <View className="box-flex not-bar">
              {order.orderItemInfos?.map(res=>(
                <Image className='main-image' src={res.mainImageUrl} />
              ))}
            </View>
            <View className="main-mask">
              共 {order.orderItemInfos?.length} 件 <Text style={{color:'#111'}} className='at-icon at-icon-chevron-right'></Text>
            </View>
          </View>:null}
          {order.orderSource == 6?
            order.orderItemInfos?.map(res=>(
              <View className="item-main" onClick={() => handleToDetail(order)}>
                <View className="main-info">
                  <View className="omit-2 h2">{res.serialNumber}</View>
                  <View className='p'>{res.rentalTime}</View>
                </View>
              </View>
            ))
          :null}
          <View className="item-footer">
            <View style={{flex:1}}>
              {order.showLJFKBtn?'需付款':'总价'}: <Text className='span' style={{fontSize: '10px'}}>￥</Text><Text className='strong' style={{fontSize: '15px',fontWeight:'600', marginRight: 'auto'}}>{order.totalPayment}</Text>
            </View>
            {order && (
              <StatusAction
                className="action"
                order={order}
                onRefresh={()=>{
                  _initData({page:1})
                }}
                onCancel={(orderId) => {
                  Taro.showModal({
                    title:'取消订单',
                    content:'您是否确定取消此订单',
                    success:res=>{
                      if(res.confirm){
                        Taro.$post('/order/users/orders/cancel',{orderId}).then(res=>{
                          _initData({page:1})
                        })
                      }
                    }
                  })
                }}
              />
            )}
          </View>
        </View>
      })}
      <View className="var-more"></View>
    </View>
  )
}
